<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="com.example.admanagement.Ad" %>
<%@ page import="com.example.admanagement.AdService" %>
<%@ page import="com.example.admanagement.AdService.Result" %>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>广告管理</title>
    <link rel="stylesheet" href="../css/admin_yuyue.css" />
    <link rel="stylesheet" href="../css/admin_nav.css" />
    <style>
        /* 全局样式 */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
            color: #333;
        }

        h1 {
            text-align: center;
            color: #007bff;
            margin: 20px 0;
            font-size: 28px;
        }

        /* 按钮通用样式 */
        button {
            cursor: pointer;
            border: none;
            border-radius: 4px;
            padding: 8px 16px;
            font-size: 16px;
            transition: all 0.3s ease;
            background-color: #007bff;
            color: white;
        }

        button:hover {
            background-color: #0056b3;
        }

        /* 模态框通用样式 */
        .admodal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
            /* 添加弹性布局使内容居中 */
            display: none;
            justify-content: center;
            align-items: center;
        }

        .admodal-content {
            background-color: #fefefe;
            padding: 20px;
            border: 1px solid #888;
            width: 50%;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
            margin: 0 auto;
            max-width: 500px;
            min-width: 300px;

        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }

        /* 新增广告按钮样式 */
        #addAdButton {
            display: block;
            margin: 0 auto 20px;
            background-color: #28a745;
        }

        #addAdButton:hover {
            background-color: #218838;
        }

        /* 表单样式 */
        form {
            margin-top: 20px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-size: 16px;
        }

        input[type="text"] {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 16px;
        }

        /* 广告列表表格样式 */
        table {
            border-collapse: collapse;
            width: 80%;
            margin-bottom: 20px;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            background-color: white;
            margin-left: 180px;
        }

        th,
        td {
            border: 1px solid #ccc;
            padding: 12px 15px;
            text-align: left;
            font-size: 16px;
        }

        th {
            background-color: #f2f2f2;
            color: #333;
            font-weight: bold;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        td img {
            max-width: 100px;
            max-height: 100px;
            border-radius: 4px;
            margin-right: 10px;
        }

        /* 操作按钮样式 */
        .action-buttons button {
            margin-right: 10px;
            background-color: #ffc107;
            color: #333;
            font-size: 14px;
            padding: 6px 12px;
        }

        .action-buttons button:hover {
            background-color: #e0a800;
        }

        .action-buttons button:last-child {
            margin-right: 0;
            background-color: #dc3545;
            color: white;
        }

        .action-buttons button:last-child:hover {
            background-color: #c82333;
        }
        .AddAd{
            position: fixed;
            bottom: 20px; /* 距离页面底部的距离，可以根据需求调整 */
            right: 20px; /* 距离页面右侧的距离，可按需更改 */
            z-index: 1000; /* 确保按钮在其他元素之上显示，可根据实际情况调整层级 */
            cursor: pointer; /* 鼠标悬停时显示手型指针 */
            background-color: #007bff; /* 按钮背景色，可自行修改 */
            color: white; /* 按钮文字颜色 */
            border: none;
            border-radius: 4px;
            padding: 4px 8px;
            font-size: 16px;
            transition: all 0.3s ease; /* 添加过渡效果，使样式变化更平滑 */
        }

        /* 为模态框内的表单添加样式 */
        .modal-content form {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .modal-content h2 {
            margin-top: 0;
            margin-bottom: 20px;
            color: #333;
        }

        .modal-content button {
            margin-top: 10px;
            margin-right: 10px;
        }
    </style>
</head>

<body>
<jsp:include page="admin.jsp" />
<div class="content">
    <jsp:include page="admin_nav.jsp" />
<!-- 添加"新增广告"按钮 -->
<button class="AddAd" id="addAdButton" onclick="showAddForm()">新增广告</button>

<!-- 新增广告的表单（模态框） -->
<div id="addAdModal" class="admodal">
    <div class="admodal-content">
        <span class="close" onclick="closeAddModal()">&times;</span>
        <h2>新增广告</h2>
        <form id="addAdForm">
            <label for="newImagePath">图片路径：</label><input type="text" id="newImagePath" required><br>
            <label for="newTitle">标题：</label><input type="text" id="newTitle" required><br>
            <label for="newLink">跳转链接：</label><input type="text" id="newLink" required><br>
            <label for="newDescription">描述：</label><input type="text" id="newDescription" required><br>
            <button type="button" onclick="addAd()">提交</button>
            <button type="button" onclick="closeAddModal()">取消</button>
        </form>
    </div>
</div>

<!-- 广告列表展示表格 -->
<table>
    <thead>
    <tr>
        <th>ID</th>
        <th>图片</th>
        <th>标题</th>
        <th>跳转链接</th>
        <th>描述</th>
        <th>操作</th>
    </thead>
    <tbody id="adTableBody">
    <%
        // 使用AdService直接获取数据库数据
        AdService.Result<List<Ad>> result = AdService.getAdsFromDatabase();
        if (result.isSuccess()) {
            List<Ad> adList = result.getData();
            for (Ad ad : adList) {
    %>
    <tr>
        <td><%= ad.getId() %></td>
        <td><img src="<%= ad.getImagePath() %>" alt="广告图片" width="100"></td>
        <td><%= ad.getTitle() %></td>
        <td><%= ad.getLink() %></td>
        <td><%= ad.getDescription() %></td>
        <td class="action-buttons">
            <button onclick="showUpdateForm(<%= ad.getId() %>)">更新</button>
            <button onclick="deleteAd(<%= ad.getId() %>)">删除</button>
        </td>
    </tr>
    <%
        }
    } else {
    %>
    <tr>
        <td colspan="7">获取广告数据失败：<%= result.getMessage() %></td>
    </tr>
    <%
        }
    %>
    </tbody>
</table>

<!-- 更新广告的模态框 -->
<div id="updateAdModal" class="admodal">
    <div class="admodal-content">
        <span class="close" onclick="closeUpdateModal()">&times;</span>
        <h2>更新广告信息</h2>
        <form id="updateAdForm">
            <input type="hidden" id="adId" value="">
            <label for="imagePath">图片路径：</label><input type="text" id="imagePath" required><br>
            <label for="title">标题：</label><input type="text" id="title" required><br>
            <label for="link">跳转链接：</label><input type="text" id="link" required><br>
            <label for="description">描述：</label><input type="text" id="description" required><br>
            <button type="button" onclick="updateAd()">提交更新</button>
            <button type="button" onclick="closeUpdateModal()">取消</button>
        </form>
    </div>
</div>

<script>
    // 更新后重新加载数据的函数
    function reloadData() {
        location.reload(); // 直接刷新页面以显示最新数据
    }

    // 修改 updateAd 函数
    function updateAd() {
        const adData = {
            id: parseInt(document.getElementById('adId').value),
            imagePath: document.getElementById('imagePath').value,
            title: document.getElementById('title').value,
            link: document.getElementById('link').value,
            description: document.getElementById('description').value
        };

        fetch('updateAd', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(adData)
        })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('更新成功');
                    closeUpdateModal();
                    reloadData(); // 使用重新加载替代 fetchAds
                } else {
                    alert('更新失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('更新失败', error);
                alert('更新失败，请查看控制台了解详情');
            });
    }

    // 显示更新广告的模态框并填充当前广告数据
    function showUpdateForm(adId) {
        fetch(`getAds`)
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    const ad = result.data.find(a => a.id === adId);
                    if (ad) {
                        const updateAdModal = document.getElementById('updateAdModal');
                        document.getElementById('adId').value = ad.id;
                        document.getElementById('imagePath').value = ad.imagePath;
                        document.getElementById('title').value = ad.title;
                        document.getElementById('link').value = ad.link;
                        document.getElementById('description').value = ad.description;
                        updateAdModal.style.display = "block";
                    }
                }
            })
            .catch(error => console.error('获取广告数据出错：', error));
    }

    // 关闭更新广告的模态框
    function closeUpdateModal() {
        document.getElementById('updateAdModal').style.display = "none";
    }

    // 显示新增广告的模态框
    function showAddForm() {
        document.getElementById('addAdModal').style.display = "block";
    }

    // 关闭新增广告的模态框
    function closeAddModal() {
        document.getElementById('addAdModal').style.display = "none";
    }

    function addAd() {
        const adData = {
            imagePath: document.getElementById('newImagePath').value,
            title: document.getElementById('newTitle').value,
            link: document.getElementById('newLink').value,
            description: document.getElementById('newDescription').value
        };

        fetch('addAd', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(adData)
        })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('添加成功');
                    closeAddModal();
                    reloadData();
                } else {
                    alert('添加失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('添加失败', error);
                alert('添加失败，请查看控制台了解详情');
            });
    }

    // 添加删除功能
    function deleteAd(adId) {
        if (!confirm('确定要删除这条广告吗？')) {
            return;
        }

        fetch('deleteAd?id=' + adId, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('HTTP错误，状态码: ' + response.status);
                }
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    alert('删除成功');
                    // 重新加载页面以显示更新后的数据
                    location.reload();
                } else {
                    alert('删除失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('删除失败:', error);
                alert('删除失败，请查看控制台了解详情');
            });
    }
</script>
</body>

</html>